package cn.com.lms.business.examRewrite.web;

import cn.com.lms.business.core.constant.ErrorEnum;
import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.examRewrite.exception.ExerciseException;
import cn.com.lms.business.examRewrite.persistence.entity.*;
import cn.com.lms.business.examRewrite.service.*;
import cn.com.lms.business.examRewrite.vo.ExerciseEditorReWriteVO;
import cn.com.lms.business.user.persistence.entity.SysUserVo;
import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;
import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.webmvc.util.WebMvcUtils;
import io.swagger.v3.oas.annotations.Parameter;
import org.apache.commons.lang3.ObjectUtils;
import org.hibernate.internal.util.StringHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/exam/exercise")
public class ExerciseReWriteController {

    @Autowired
    ExerciseReWriteService exerciseReWriteService;

    @Autowired
    QuestionCategoryWriteVoService questionCategoryWriteVoServer;

    @Autowired
    ExerciseEmployeeReWriteVoService exerciseEmployeeReWriteVoService;

    @Autowired
    QuestionReWriteService questionReWriteService;

    @Autowired
    ExerciseQuestionReWriteService exerciseQuestionReWriteService;

    @Autowired
    UserReWriteService userReWriteService;

    /**
     * 试题中心的主页数据
     * @param request
     * @return
     */
    @GetMapping("/pageReWrite")
    public ResponseResult<Page<ExerciseReWriteVo>> Page(HttpServletRequest request){
        String keyWord = request.getParameter("keyWord");
        // 分页和排序 WebMvcUtils
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "ee.create_time"));
        // 基本的sql 返回类型 QueryHelpBean
        QueryHelpBean queryHelpBean = ExerciseReWriteService.getQueryHelpBean();
        queryHelpBean.setPageable(pageable);
        // 判断keyWord是否为空
        if (StringHelper.isNotEmpty(keyWord)){
            // 添加条件
            IExpression expression = CompareExpression.build("ee.exercise_name", CompareType.like, keyWord);
            queryHelpBean.addWhere(expression);
        }
        // 判断字段is_delete = 0 未删除
        IExpression expression1 = CompareExpression.build("ee.is_delete", CompareType.equal, false);
        queryHelpBean.addWhere(expression1);
        // 通过sql语句查出数据 Page<ExerciseRewriteVo>
        Page<ExerciseReWriteVo> exerciseVos = exerciseReWriteService.findAll(queryHelpBean);
        // 返回封装好的数据
        return ResponseResult.success(exerciseVos);
    }

    /**
     * 试题页面详情
     * @param id
     * @return
     */
    @GetMapping("/oneReWrite/{id}")
    public ResponseResult<ExerciseEditorReWriteVO>  getById(@Parameter(name = "id", required = true) @PathVariable("id") Long id){
        ExerciseEditorReWriteVO exerciseEditorReWriteVO = new ExerciseEditorReWriteVO();
        Optional<ExerciseReWrite> exerciseReWriteOptional = this.exerciseReWriteService.findById(id);
        ExerciseReWrite exerciseReWrite = exerciseReWriteOptional.get();
        BeanUtils.copyProperties(exerciseReWrite,exerciseEditorReWriteVO);
        if (!exerciseReWriteOptional.isPresent()) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        // 获取题库名称+类型+试题数 QuestionReWrite
        List<QuestionCategoryReWriteVo> questionReWriteList =  questionCategoryWriteVoServer.getQuestionNameAddTypeAddCountById(exerciseReWrite.getId());
        exerciseEditorReWriteVO.setQuestionCategoryReWriteVoList(questionReWriteList);

        // 获取人员 ExerciseEmployeeReWrite
        List<UserReWrite> all = userReWriteService.getEmployeeById(exerciseReWrite.getId());
        exerciseEditorReWriteVO.setExerciseEmployeeList(all);
        // 返回数据
        return ResponseResult.success(exerciseEditorReWriteVO);
    }

    /**
     * 更新数据
     * @param exerciseReWrite
     * @return
     */
    @PostMapping("/updateReWrite")
    public ResponseResult<ExerciseReWrite> UpdateExerciseReWrite(@RequestBody ExerciseReWrite exerciseReWrite){
        if (ObjectUtils.isEmpty(exerciseReWrite.getId())) {
            throw new BusinessException(ErrorEnum.PARAMETER_CANNOT_BE_EMPTY.getMessage(), "" + ErrorEnum.PARAMETER_CANNOT_BE_EMPTY.getCode());
        }

        Optional<ExerciseReWrite> optionalExerciseReWrite = exerciseReWriteService.findById(exerciseReWrite.getId());
        if (!optionalExerciseReWrite.isPresent()){
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        ExerciseReWrite exerciseReWriteData = optionalExerciseReWrite.get();

        // 通过employeeId获取数据 前端传过来的数据
        List<ExerciseEmployeeReWriteVo> uniqueEmployee = exerciseEmployeeReWriteVoService.getUniqueEmployeeId(exerciseReWrite);


        // 通过QuestionId获取数据 前端传过来的数据
        List<ExerciseQuestionReWrite> uniqueQuestion = exerciseQuestionReWriteService.getUniqueQuestionId(exerciseReWrite);

        // 获取数据保存
        // 获取当前用户
        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        exerciseReWriteData.setModifyBy(String.valueOf(sysUser.getId()));
        exerciseReWriteData.setModifyName(sysUser.getCname());
        exerciseReWriteData.setModifyTime(new Date());
        exerciseReWriteData.setExerciseName(exerciseReWrite.getExerciseName());
        exerciseReWriteData.setExerciseEmployeeList(uniqueEmployee);
        exerciseReWriteData.setExerciseQuestionList(uniqueQuestion);
        exerciseReWriteService.updateExercise(exerciseReWriteData);


        return ResponseResult.success(exerciseReWriteData);
    }

    /**
     * 启用
     * @param id
     * @return
     */
    @PostMapping("/enableReWrite")
    @Transactional // 更新操作要添加事务
    public ResponseResult<Integer> enableById(@RequestBody List<Long> id){
        Integer result = exerciseReWriteService.enableById(true,id);
        return ResponseResult.success(result);

    }

    /**
     * 禁用
     * @param id
     * @return
     */
    @PostMapping("/disableReWrite")
    @Transactional // 更新操作要添加事务
    public ResponseResult<Integer> disableById(@RequestBody List<Long> id){
        Integer result = exerciseReWriteService.disableById(true,id);
        return ResponseResult.success(result);
    }

    /**
     * 删除、批量删除
     * @param id
     * @return
     */
    @PostMapping("/deleteReWrite")
    public ResponseResult<Integer> deletesById(@RequestBody List<Long> id){
        Integer result = exerciseReWriteService.deletesById(true,id);
        return ResponseResult.success(result);
    }


    /**
     * 保存
     * @param exerciseReWrite
     * @return
     */
    @PostMapping("/saveReWrite")
    public ResponseResult<ExerciseReWrite> saveExerciseReWrite(@RequestBody ExerciseReWrite exerciseReWrite){
        // 判断名称、科目、人员、创建人是否同时为true
        Boolean result = exerciseReWriteService.Allequal(exerciseReWrite);
        if (result){
            // 异常 试卷已存在
            throw new ExerciseException(ErrorEnum.EXERCISE_EXIST.getCode(),ErrorEnum.EXERCISE_EXIST.getMessage());
        }else {
            // 保存数据
            exerciseReWriteService.saveExercise(exerciseReWrite);
            return ResponseResult.success(exerciseReWrite);
        }
    }




}
